/**
 * TeacherController
 *
 * @description :: Server-side logic for managing teachers
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
	createTeacher:function(req,res){
      let data = req.body;
    //   console.log(data);
    //   res.json({success:false});
      People.create({name:data.name},(err,tar)=>{
          if(err) {
              res.json({
                  success:false,
                  message:'创建教师失败'
              });
          }
          Teacher.create({
              PeopleId:tar.id,
              PhoneNumber:data.phoneNumber,
              WorkId:data.workId
          },(err,tarT)=>{
              if(err){
                  People.destroy({id:tar.id},()=>{
                      res.json({
                          success:false,
                          message:'创建教师失败'
                      });
                  })
              }else{
                  res.json({
                      success:true,
                      message:'创建教师成功',
                      data:{
                          id:tar.id
                      }
                  });
              }
          })
      })
    },
    updateTeacher:function(req,res){
        let attr = req.body;

        Database.update(Teacher,
            {PeopleId:req.body.id}
            ,{PhoneNumber:attr.phoneNumber,WorkId:attr.workId}).then(()=>{
            // console.log('54321');
            res.json({success:true});
        }).catch((err)=>{
            // console.log(err);
            // console.log('12345');
            res.json({success:false});
        })
    },
    getTeacher:function(req,res){
        Teacher.find({},(err,targets)=>{
            if(err) throw err;
            let jobs = _.map(targets,(t)=>(callback)=>{
                People.findOne({id:t.PeopleId},(err,p)=>{
                    callback(err,{
                        name:p.name,
                        phoneNumber:t.PhoneNumber,
                        workId:t.WorkId,
                        id:p.id});
                })
            })
            async.series(jobs,(err,tars)=>{
                if(err) throw err;
                res.json(tars);
            })
        });
    },
    deleteTeacher:function(req,res){
        // console.log(req.body);
        Database.destroy(Teacher,{PeopleId:req.body.id}).then(
            Database.destroy(People,{id:req.body.id})
        ).then(()=>{
            res.json({success:true});
        }).catch(()=>{
            res.json({success:false});
        })

    }
};
